//    Copyright (C) Kherty.  All rights reserved.
using System.Collections.Generic;
using OpenLS.Spreadsheet.Extensibility;

namespace OpenLS.Spreadsheet.StandardAddIn.Database
{
    internal abstract class DatabaseCriteria
    {
        public abstract bool Matches(IRange source, int rowIndex);

        public static DatabaseCriteria Create(IWorkbook workbook, IRange source, IRange range)
        {
            OrDatabaseCriteria result = new OrDatabaseCriteria();
            Dictionary<string, int> columns = new Dictionary<string, int>();
            for (int i = 0; i < source.ColumnSpan; i++)
            {
                object o = source[0, i].Value;
                if (o == null)
                    continue;
                string s = o.ToString();
                columns.Add(s, i);
            }
            for (int row = 1; row < range.RowSpan; row++)
            {
                AndDatabaseCriteria and = new AndDatabaseCriteria();
                for (int column = 0; column < range.ColumnSpan; column++)
                {
                    object o = range[row, column].Value;
                    if (o == null)
                        continue;
                    and.Criteria.Add(
                        new SingleDatabaseCriteria(workbook, o.ToString(), columns[range[0, column].Value.ToString()]));
                }
                if (and.Criteria.Count > 0)
                    result.Criteria.Add(and);
            }
            return result;
        }
    }
}